import { queryVehicleDetail } from '../../services/vehicle'
import { inspectorSaveOrder } from '../../services/order'
import { queryInstDetailInfo } from '../../services/project'
import { queryUrlsBySpaceId, queryRealData } from '../../services/inspect'
import { updateInstInfo } from '../../services/inspect'
import dayjs from 'dayjs'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderId:"",
    vehicleId:"",
    instId:"",
    spaceId:"",
    vehicleInfo:{},
    inspectInfo:{},
    urlsList:[],
    allInfoList:[],
    allInfoUrlList:['ChargerOutCur', 'ChargerOutVol', 'SingAccBatMaxVol','VehBatRatedCapacity', 'VehBatRatedTotalVol', 'VehBatNomEnergy', 'BatMaxVol', 'MANUFACTURER', 'PRODUCTIONDATE', 'BMSMaxAccCharVol', 'SingMaxAccCharVol', 'SumCharTime', 'SOC', 'StopSOC'],
    topUrlInfo:[],
    topInfoUrlList:['ChargerOutCur', 'ChargerOutVol', 'SingAccBatMaxVol'],
    socUrlInfo:[],
    socInfoUrlList:['SOC', 'StopSOC'],
    contUrlInfo:[],
    contInfoUrlList:['VehBatRatedCapacity', 'VehBatRatedTotalVol', 'VehBatNomEnergy', 'BatMaxVol', 'MANUFACTURER', 'PRODUCTIONDATE', 'BMSMaxAccCharVol', 'SingMaxAccCharVol'],
    timer: null,
    fieldList:[
      {
        name:"整车动力蓄电池系统额定容量",
        value:""
      },
      {
        name:"整车动力蓄电池系统额定总电压",
        value:""
      },
      {
        name:"动力蓄电池标称总能量",
        value:""
      },
      // {
      //   name:"行驶里程",
      //   value:"5035km"
      // },
      // {
      //   name:"电池类型",
      //   value:"磷酸铁理电池"
      // },
      {
        name:"生产厂商",
        value:""
      },
      {
        name:"生产日期",
        value:""
      },
      // {
      //   name:"充电次数",
      //   value:"100次"
      // },
      {
        name:"最高允许充电总电压",
        value:""
      },
      {
        name:"单体电池最高允许充电电压",
        value:""
      },
      {
        name:"累计充电时间",
        value:""
      },
      // {
      //   name:'当前荷电状态SOC',
      //   value:""
      // },
      // {
      //   name:"中止荷电状态SOC",
      //   value:""
      // }
      // {
      //   name:"充电结束时间",
      //   value:"2023-06-06 14:21:23"
      // }
    ],
    startSoc:"",
    endSoc:"",
    isInitSoc:true,
    instInfo:{},
    showInstDate: true,
    hasData: true,
    headerValue1: '',
    headerValue2: '',
    headerValue3: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(!options){
      return
    }
    let orderId = options.orderId
    let vehicleId = options.vehicleId
    let instId = options.instId
    let spaceId = options.spaceId
    this.setData({
      orderId,
      vehicleId,
      instId,
      spaceId
    })
    if(vehicleId){
      this.getVehicleDetail(vehicleId)
    }
    if(instId){
      this.getInstDetailInfo(instId)
    }
    if(spaceId){
      this.getInfoListBySpaceId(spaceId)
    }
  },

  onShow(){
    let vehicleId = this.data.vehicleId
    let instId = this.data.instId
    let spaceId = this.data.spaceId

    if(vehicleId){
      this.getVehicleDetail(vehicleId)
    }
    if(instId){
      this.getInstDetailInfo(instId)
    }
    if(spaceId){
      this.getInfoListBySpaceId(spaceId)
    }
  },

  onHide(){
    if(this.data.timer){
      clearInterval(this.data.timer)
    }
  },

  onUnload(){
    if(this.data.timer){
      clearInterval(this.data.timer)
    }
  },

  async getVehicleDetail(vehicleId){
    let res = await queryVehicleDetail(vehicleId)
    if(res.code === 200){
      let vehicleInfo = res.data
      this.setData({
        vehicleInfo
      })      
    }
  },

  async getInstDetailInfo(instId){
    let res = await queryInstDetailInfo(instId)
    if(res.code === 200){
      let instInfo = res.data
      let resJson = res.data.itemJson
      if(resJson){
        let inspectInfo = typeof resJson == 'string' ? JSON.parse(resJson) : resJson 
        this.setData({
          inspectInfo,
          instInfo
        })
      }
    }
  },

  async getInfoListBySpaceId(spaceId){
    let res = await queryUrlsBySpaceId({ spaceId })
    if(res.code === 200){
      let urlsList = res.rows
      this.getUrlIds(this.data.allInfoUrlList, urlsList)
      this.setData({
        urlsList
      })
    }
  },

  getUrlIds(urls, urlsList){
    let ids = []
    urls.forEach(item => {
      let searchItem = urlsList.find( iten => iten.url.toUpperCase() == item.toUpperCase())
      ids.push(searchItem.id)
    })
    
    this.getRealData(ids)
    const _this = this
    let timer = setInterval(function(){
      _this.getRealData(ids)
    }, 3000)
    this.setData({
      timer
    })
  },

  getUrlInfos(urls, urlsList){
    let urlInfos = []
    urls.forEach(item => {
      let searchItem = urlsList.find( iten => iten.url.toUpperCase() == item.toUpperCase())
      urlInfos.push(searchItem)
    })
    return urlInfos
  },

  async getRealData(ids){
    let allInfoList = []
    let orderId = this.data.orderId
    let res = await queryRealData(ids)
    if(res.code == 200){
      allInfoList = res.data
      let topUrlInfo = this.getUrlInfos(this.data.topInfoUrlList, allInfoList)

      if(topUrlInfo[1] && topUrlInfo[1]['timestamp']){
        let nowDate = dayjs().format('YYYY-MM-DD HH:mm:ss')
        let lastInspectTime = dayjs(topUrlInfo[1]['timestamp']).format('YYYY-MM-DD HH:mm:ss')
        let difftime = dayjs(nowDate).diff(lastInspectTime)
        // let hasData = this.data.hasData
        if(difftime > 300000){
          console.log("超过五分钟了",difftime)
          // wx.showLoading({
          //   title: '暂无数据...',
          // })
          this.setData({
            hasData: false,
            allInfoList: []
          })
          return
        }else{
          // wx.hideLoading()
          this.setData({
            hasData: true
          })
        }
      }

      let socUrlInfo = this.getUrlInfos(this.data.socInfoUrlList, allInfoList)
      let fieldList = this.getUrlInfos(this.data.contInfoUrlList, allInfoList)
      
      let headerValue1 = topUrlInfo[0] ? parseFloat(Number(topUrlInfo[0]['value']).toFixed(2))  : ""
      let headerValue2 = topUrlInfo[1] ? parseFloat(Number(topUrlInfo[1]['value']).toFixed(2))  : ""
      let headerValue3 = topUrlInfo[2] ? parseFloat(Number(topUrlInfo[2]['value']).toFixed(2))  : ""


      let startSoc = this.data.startSoc
      if(this.data.isInitSoc){
        let storageStartSoc = wx.getStorageSync( `${orderId}-charging-init-start-soc`)
        if(!storageStartSoc){
          wx.setStorageSync(`${orderId}-charging-init-start-soc`, socUrlInfo && socUrlInfo.length ? socUrlInfo[0]['value'] : 0)
        }
        startSoc = storageStartSoc || (socUrlInfo && socUrlInfo.length ? socUrlInfo[0]['value'] : 0)
        
        
        let isInitSoc = false
        this.setData({
          isInitSoc
        })
      }

      let endSoc = socUrlInfo && socUrlInfo.length ? socUrlInfo[0]['value'] : 0

      this.handleSaveEndTime()

      this.setData({
        allInfoList,
        topUrlInfo,
        socUrlInfo,
        fieldList,
        startSoc,
        endSoc,
        headerValue1,
        headerValue2,
        headerValue3
      })
    }
  },

  handleInspectAgain(){},

  async handleSaveEndTime(){
    this.setData({
      [`instInfo.detectEndTime`]: dayjs().format("YYYY-MM-DD HH:mm:ss")
    })

    let data = {
      id: this.data.instId,
      detectEndTime: this.data.instInfo.detectEndTime,
    }
    let saveRes = await updateInstInfo(data)

  },

  async handleSubmit(){
    let data = {
      id: this.data.instId,
      status: 3,
    }
    let submitRes = await updateInstInfo(data)
    if(submitRes.code === 200){
      if(this.data.timer){
        clearInterval(this.data.timer)
      }
      wx.reLaunch({
        url: `/pages/order-handle/order-handle?id=${this.data.orderId}&vehicleId=${this.data.vehicleId}`,
      })
    }
  }

    

})